<?php
namespace App\Lib\Upload;
use App\Lib\Utils;
class Base {
    /**
     * 上传的file - key
     * @var string
     */
    public $type = '';
    public $file = '';
    public $size = '';
    public function __construct($request,$type=null)
    {
        $this->request = $request;
        if (empty($type)) {
            $files = $this->request->getSwooleRequest()->files;
            $types = array_keys($files);
            $this->type = $types[0];
        } else {
            $this->type = $type;
        }


    }
    public function upload() {
        //上传类型是否合法
        if ($this->type != $this->fileType) {
            return false;
        }
        //获取上传的文件信息
        $video = $this->request->getUploadedFile($this->type);
        $this->size = $video->getSize();
        $this->checkSize();
        //获取文件名称
        $fileName = $video->getClientFileName();
        $this->clientMediaType = $video->getClientMediaType();
        $this->checkMediaType();
        //得到文件路径
        $file = $this->getFile($fileName);
        //将文件上传到本地
        $flag = $video->moveTo($file);
        if (!empty($flag)) {
            //返回文件路径
            return $this->file;
        }
        return false;
    }
    public function getFileName() {
        $video = $this->request->getUploadedFile($this->type);
        $fileName = $video->getClientFileName();
        return $fileName;
    }
    public function getFile($fileName) {
        $pathinfo = pathinfo($fileName);
        $extension = $pathinfo['extension'];
        $dirname = "/".$this->type."/".date('Y')."/".date('m');
        $dir = EASYSWOOLE_ROOT."/webroot".$dirname;
        if (!is_dir($dir)) {
            mkdir($dir,0777,true);
        }
        $basename = "/" .Utils::getFileKey($fileName). ".".$extension;
        $this->file = $dirname.$basename;
        return $dir.$basename;
    }
    //检验文件（是否规定的文件后缀名）是否合法
    public function checkMediaType() {
        $clientMediaType = explode('/',$this->clientMediaType);
        $clientMediaType = $clientMediaType[1] ?? "";
        var_dump($clientMediaType);
        if (empty($clientMediaType)) {
            throw new \Exception("上传{$this->type}文件不合法");
        }
        if (!in_array($clientMediaType,$this->fileExtTypes)) {
            throw new \Exception("上传{$this->type}文件不合法");
        }
        return true;
    }
    //检验文件大小
    public function checkSize() {
        var_dump($this->size);
        if (empty($this->size)) {
            return false;
        }
        if ($this->maxSize < $this->size) {
            return false;
        }
    }
}